package com.yiren.manager.ctrl.desk;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yiren.core.exception.MyException;
import com.yiren.core.exception.SwallowException;
import com.yiren.core.repository.utils.QueryResult;
import com.yiren.core.utils.HTTPResult;
import com.yiren.core.utils.JsonMapperTool;
import com.yiren.core.utils.UUIDGenerator;
import com.yiren.entity.YrElder;
import com.yiren.entity.YrElderFamilyMember;
import com.yiren.entity.YrFilialScore;
import com.yiren.entity.YrStaffInfo;
import com.yiren.manager.ctrl.GenericController;
import com.yiren.manager.form.desk.YrFilialScoreForm;
import com.yiren.manager.form.elder.YrElderFamilyMemberForm;
import com.yiren.manager.form.elder.YrElderForm;
import com.yiren.manager.form.elder.YrFilialScoreRecordForm;
import com.yiren.manager.service.iface.department.YrStaffInfoService;
import com.yiren.manager.service.iface.desk.YrFilialScoreService;
import com.yiren.manager.service.iface.elder.YrElderFamilyMemberService;
import com.yiren.manager.service.iface.elder.YrElderService;
import com.yiren.manager.utils.ObjectUtils;

@RequestMapping("filialScore")
@Controller
public class YrFilialScoreController extends GenericController<YrFilialScoreForm, YrFilialScore>{

	@Autowired
	private YrFilialScoreService selfService;
	
	@Autowired
	private YrElderService elderService;
	
	@Autowired
	private YrElderFamilyMemberService elderFamilyMemberService;
	
	@Autowired
	private YrStaffInfoService staffInfoService;
	
	//保存实体
	@RequestMapping("/save")
	@ResponseBody
	public HTTPResult<YrFilialScoreForm> save(String data) throws SwallowException, MyException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException{
		HTTPResult<YrFilialScoreForm> result = new HTTPResult<YrFilialScoreForm>();
		JsonMapperTool tool = new JsonMapperTool(data);
		YrFilialScoreForm form = tool.mapper("filialScore", YrFilialScoreForm.class);
		if(null==form){
			throwExp("param.error");
		}
		if(null==form.getFilialScoreId()||form.getFilialScoreId().isEmpty()){
			form.setFilialScoreId(UUIDGenerator.getUUID());
			form.setCreateTime(new Date());
		}
		form.setUpdateTime(new Date());
		YrFilialScore entity = ObjectUtils.objectToObject(form, YrFilialScore.class);
		selfService.save(entity);
		
		return result;
	}
	
	/**
	 * 孝行分查询
	 * @param month
	 * @param elderSearchVal
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("find")
	@ResponseBody
	public HTTPResult<YrFilialScoreRecordForm> find(String month,String elderSearchVal) throws Exception{
		HTTPResult<YrFilialScoreRecordForm> result = new HTTPResult<YrFilialScoreRecordForm>();
		YrFilialScoreRecordForm form = new YrFilialScoreRecordForm();
		String sqlWhere = "name=?1 OR card_id=?2";
		QueryResult<YrElder> qrElder = elderService.find(YrElder.class, sqlWhere, new Object[]{elderSearchVal,elderSearchVal});
		if(qrElder.getTotalRecord()>0){
			YrElder elder = qrElder.getResultList().get(0);
			form.setElderForm(ObjectUtils.objectToObject(elder, YrElderForm.class));
			sqlWhere = "elder_id=?1 AND DATE_FORMAT(create_time,'%Y-%m') = ?2";
			QueryResult<YrFilialScore> qrFilialScore = selfService.find(YrFilialScore.class, sqlWhere, new Object[]{elder.getElderId(),month});
			List<YrFilialScoreForm> filialScoreForms = new ArrayList<YrFilialScoreForm>();
			for(YrFilialScore filialScore : qrFilialScore.getResultList()){
				YrFilialScoreForm filialScoreForm = toForm(filialScore);
				YrElderFamilyMember elderFamilyMember = elderFamilyMemberService.findOne(filialScore.getFamilyMemberId());
				if(null!=elderFamilyMember){
					YrElderFamilyMemberForm elderFamilyMemberForm = ObjectUtils.objectToObject(elderFamilyMember, YrElderFamilyMemberForm.class);
					YrStaffInfo staffInfo = staffInfoService.findOne(elderFamilyMember.getCreateId());
					if(null!=staffInfo){
						elderFamilyMemberForm.setRecorder(staffInfo.getName());
					}
					filialScoreForm.setElderFamilyMemberForm(elderFamilyMemberForm);
				}
				filialScoreForms.add(filialScoreForm);
			}
			form.setFilialScoreForms(filialScoreForms);
		}
		List<YrFilialScoreRecordForm> filialScoreRecordForms = new ArrayList<YrFilialScoreRecordForm>();
		filialScoreRecordForms.add(form);
		result.setData(filialScoreRecordForms);
		
		return result;
	}
	/**
	 * 孝行分排行
	 * @param monthStart
	 * @param monthEnd
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("seniority")
	@ResponseBody
	public HTTPResult<YrFilialScoreForm> seniority(String monthStart,String monthEnd) throws Exception{
		HTTPResult<YrFilialScoreForm> result = new HTTPResult<YrFilialScoreForm>();
		String sqlWhere = "DATE_FORMAT(create_time,'%Y-%m')>?1 AND DATE_FORMAT(create_time,'%Y-%m')<?2";
		QueryResult<YrFilialScore> qr = selfService.find(YrFilialScore.class, sqlWhere, new Object[]{monthStart,monthEnd});
		
		Map<String, YrFilialScore> map = new HashMap<String, YrFilialScore>();
		for(YrFilialScore entity : qr.getResultList()){
			if(map.containsKey(entity.getFamilyMemberId())){
				YrFilialScore score = map.get(entity.getFamilyMemberId());
				score.setScore(score.getScore()+entity.getScore());
				map.put(entity.getFamilyMemberId(), score);
			}else{
				map.put(entity.getFamilyMemberId(), entity);
			}
		}
		List<YrFilialScore> list = seniorityScore(map);
		List<YrFilialScoreForm> formList = new ArrayList<YrFilialScoreForm>();
		for(YrFilialScore score : list){
			YrFilialScoreForm form = toForm(score);
			YrElder elder = elderService.findOne(score.getElderId());
			if(null!=elder){
				form.setElderForm(ObjectUtils.objectToObject(elder, YrElderForm.class));
			}
			YrElderFamilyMember elderFamilyMember = elderFamilyMemberService.findOne(score.getFamilyMemberId());
			if(null!=elderFamilyMember){
				YrElderFamilyMemberForm elderFamilyMemberForm = ObjectUtils.objectToObject(elderFamilyMember,YrElderFamilyMemberForm.class);
				form.setElderFamilyMemberForm(elderFamilyMemberForm);
			}
			formList.add(form);
		}
		result.setData(formList);
		return result;
	}
	
	/**
	 * 分数排序
	 * @param map
	 * @return
	 */
	private List<YrFilialScore> seniorityScore(Map<String, YrFilialScore> map){
		
		List<YrFilialScore> list = new ArrayList<YrFilialScore>();
		for(Map.Entry<String, YrFilialScore> entry : map.entrySet()){
			list.add(entry.getValue());
		}
		YrFilialScore temp = null;
		for(int i=0,c=list.size()-1;i<c;i++){
			for (int j =0; j < c-i; j++) { 
				if(list.get(j).getScore()>list.get(j+1).getScore()){
					temp = list.get(j);
					list.set(j,list.get(j+1));
					list.set(j+1,temp);
				}
			}
		}
		return list;
	}
	@Override
	public YrFilialScoreForm toForm(YrFilialScore e) throws Exception {
		YrFilialScoreForm form = ObjectUtils.objectToObject(e, YrFilialScoreForm.class);
		return form;
	}

	@Override
	public YrFilialScore toEntity(YrFilialScoreForm f) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
